﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace MultiThread
{
    public class TreadPoolOperator
    {
        private static int count1 =0;
        private static int count2 =0;
        private static int count3 =0; 
        private static int count4 =0;
        private static List<string> eggs;
        private static object obj = new object();
        public static void CreateMultiThread()
        {
            eggs = new List<string>();
            for (int i = 1; i <= 50; i++)
            {
                string egg = "egg" + i.ToString();
                eggs.Add(egg);
            }
            //{0,10}\t{1,-5}\t{2,8}  0,1,2是参数位置，  10,5，8是所占位宽的最小值，可自动增加，-5 表示左对齐，5表示右对齐
            Console.WriteLine("{0,-10}\t{1,-5}\t{2,-8}", "ThreadName", "Egg", "Time");
            ThreadPool.QueueUserWorkItem(TreadPoolOperator.RunThread1);
            ThreadPool.QueueUserWorkItem(TreadPoolOperator.RunThread2);
            ThreadPool.QueueUserWorkItem(TreadPoolOperator.RunThread3);
            ThreadPool.QueueUserWorkItem(TreadPoolOperator.RunThread4);

        }
        public static void RunThread1(object obj)
        {
            if (count1 == 0)
            {
                Thread.CurrentThread.Name = "Thread1";
            }
            count1++;
            GetAnEgg();
            Thread.Sleep(1000);
            RunThread1( obj);

        }
        public static void RunThread2(object obj)
        {
            if (count2 == 0)
            {
                Thread.CurrentThread.Name = "Thread2";
            }
            count2++;
            GetAnEgg();
            Thread.Sleep(2000);
            RunThread2(obj);
        }
        public static void RunThread3(object obj)
        {
            if (count3 == 0)
            {
                Thread.CurrentThread.Name = "Thread3";
            }
            count3++;
            GetAnEgg();
            Thread.Sleep(3000);
            RunThread3(obj);
        }
        public static void RunThread4(object obj)
        {
            if (count4 == 0)
            {
                Thread.CurrentThread.Name = "Thread4";
            }
            count4++;
            GetAnEgg();
            Thread.Sleep(4000);
            RunThread4(obj);
        }
        public static void GetAnEgg()
        {
            lock (obj)
            {
                if (eggs.Count == 0)
                {

                    return;
                }
                string egg = eggs[0];
                Console.WriteLine("{0,-10}\t{1,-5}\t{2,-8}",Thread.CurrentThread.Name ,egg , DateTime.Now.ToString("mm--ss"));
                eggs.Remove(egg);


            }
        }
    }
}
